package com.ssy.wireless.web.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.wireless.entity.Hotspot;
import com.ssy.wireless.util.DateUtils;
import com.ssy.wireless.web.service.HotspotService;
import com.ssy.wireless.web.vo.Marker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by cofey on 16/11/18.
 */
@RestController
public class IndexController {
    @GetMapping("/")
    public ModelAndView login() {
        return new ModelAndView("login");
    }

    @GetMapping("/index")
    public ModelAndView index() throws JsonProcessingException {
        List<Hotspot> hotspots = hotspotService.find(null);
        List<Marker> markers = new ArrayList();
        hotspots.stream().forEach(hotspot -> {
            Marker marker = new Marker();
            marker.setId(hotspot.getId());
            marker.setType(hotspot.getType());
            marker.setTitle(hotspot.getName());
            marker.setPoint(hotspot.getLongitude() + "," + hotspot.getLatitude());
            marker.setStatus(hotspot.getRunStatus().intValue() == 1 ? "正常" : "故障");
            markers.add(marker);
        });

        String markerJsonStr = new ObjectMapper().writeValueAsString(markers);
        Map<String, Object> result = new HashMap<>();
        result.put("markers", markerJsonStr);
        result.put("rumTime", getRumTime(DateUtils.secondsBetween(hotspotService.selectTheFirstDate(), new Date())));
        result.put("tel", hotspotService.selectTypeCount(1));
        result.put("mob", hotspotService.selectTypeCount(2));
        return new ModelAndView("index", result);
    }

    private String getRumTime(long mss) {
        String rumTime = "";
        long days = mss / (60 * 60 * 24);
        long hours = (mss % (60 * 60 * 24)) / (60 * 60);
        long minutes = (mss % (60 * 60)) / 60;
        long seconds = mss % 60;
        if (days > 0) {
            rumTime = days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
        } else if (hours > 0) {
            rumTime = hours + "小时" + minutes + "分钟" + seconds + "秒";
        } else if (minutes > 0) {
            rumTime = minutes + "分钟" + seconds + "秒";
        } else {
            rumTime = seconds + "秒";
        }
        return rumTime;
    }

    @GetMapping("/build")
    public ModelAndView build() {
        return new ModelAndView("build");
    }

    @GetMapping("/logout")
    public ModelAndView logout() {
        return new ModelAndView("login");
    }

    @Autowired
    private HotspotService hotspotService;
}
